package org.example.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.models.R;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {

    ObjectMapper objectMapper= new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        R<Object> error = R.error(401, exception.getMessage());
        String json = objectMapper.writeValueAsString(error);
        response.getWriter().print(json);
//        response.getWriter().print("登录失败");
    }
}
